package net.lovesrc.allin.biz.jobtask;

import com.alibaba.fastjson.JSONObject;
import com.google.common.collect.Lists;
import net.lovesrc.allin.biz.lbc.LbcRegisterService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Profile;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

@Service
//@Profile("geliclive")
public class JobTaskServiceImpl2 extends JobTaskService {

    @Autowired
    private LbcRegisterService lbcRegisterService;

    @Override
    public void process() {
        List<String> types = tryGetProperties(List.class, new ArrayList<String>(), "JobTaskProcess_Types");
        if (types.isEmpty()) {
            types = jdbcTemplate.queryForList("select distinct type from t_job_task where done = 0 and status = 'NEW' order by rand()", String.class);
        }
        List<JSONObject> rows = Lists.newArrayList();
        for (String type : types) {
            // check failure
            List<JSONObject> doneRows = queryForRows(jdbcTemplate, "select * from t_job_task where done = 1 and type = ? order by id desc limit 100", type);
            if (doneRows.size() > 4) {
                long failureDoneRows = doneRows.stream().filter(r -> "failure".equalsIgnoreCase(r.getString("status"))).count();
                if ((1.0 * failureDoneRows / doneRows.size()) >= 0.3) {
                    notificationService.oneEmailIn10Minutes(type + "，失败过多，请检查");
                    continue;
                }
            }
            JSONObject row = queryForRow(jdbcTemplate, "select * from t_job_task where done = 0 and type = ? order by rand() limit 1", type);
            if (row != null) {
                rows.add(row);
            }
        }
        for (JSONObject row : rows) {
            Long id = row.getLong("id");
            String type = row.getString("type");
            execute("JobTask", id, () -> {
                JSONObject biz = row.getJSONObject("biz");
                jdbcTemplate.update("update t_job_task set status = 'ING' where id = ?", id);
                try {
                    switch (type) {
                        case "LBC_NEW_REGISTER":
                            doLbcNewRegister(biz);
                            break;
                        default:
                            return;
                    }
                    // success
                    jdbcTemplate.update("update t_job_task set done = 1, status = 'SUCCESS', doneTime = ? where id = ?", new Date(), id);
                } catch (Exception e) {
                    // failure
                    jdbcTemplate.update("update t_job_task set done = 1, status = 'FAILURE', doneTime = ?, errorMsg = ? where id = ?", new Date(), e.getMessage(), id);
                }
            });
        }
    }

    private void doLbcNewRegister(JSONObject biz) {
        String promotionCode = biz.getString("promotionCode");
        lbcRegisterService.register(promotionCode);
    }

    @Override
    public boolean isrun() {
        return false;
    }
}
